package com.checx.reload;

import com.checx.loader.MyClassLoader;

import java.lang.reflect.Method;

public class Server {

    private Object service;

    public void updateService(String path) {
        // 编译完成后要把Service.class移走，否则MyClassLoader委托父加载器AppClassLoader加载时，
        // AppClassLoader会在classpath下找到Service.class并加载它，于是每次com.checx.reload.Service
        // 都会由AppClassLoader加载，其实只用加载一次。而不是由MyClassLoader加载
        MyClassLoader myClassLoader = new MyClassLoader(path);
        Class<?> cls = myClassLoader.loadClass("com.checx.reload.Service");
        try {
            service = cls.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void processRequest() {
        try {
            Method run = service.getClass().getMethod("run");
            run.invoke(service);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
